package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: xuesm
 * @date: 2025/1/1 17:27
 */
@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询一级分类
     * 跳首页
     * @param model
     * @return
     */
    @GetMapping({"/", "index.html"})
    public String indexPage(Model model){
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categorys", categoryEntities);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catalog2Vo>> getCatalogJson(){
//        Map<String, List<Catalog2Vo>> map = categoryService.getCatalogJson(); // 最原始，每一层级都查询
//        Map<String, List<Catalog2Vo>> map = categoryService.getCatalogJson2();  // 优化， 查询一次库
//        Map<String, List<Catalog2Vo>> map = categoryService.getCatalogJson3();  // 进一步优化加入缓存逻辑
        Map<String, List<Catalog2Vo>> map = categoryService.getCatalogJson6();  // 测试springcache
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        // 1. 获取一把锁， 只要锁的名字一样就是同一把锁
        RLock lock = redissonClient.getLock("my-lock");
        // 2. 加锁
        lock.lock(10, TimeUnit.SECONDS);
        try {
            System.out.println("加锁成功， 执行业务..." + Thread.currentThread().getName());
//            Thread.sleep(20000);
        }catch (Exception e){
        }finally {
            // 3. 解锁
            System.out.println("释放锁..." + Thread.currentThread().getName());
            lock.unlock();
        }
        return "hello";
    }

    @GetMapping("/write")
    @ResponseBody
    public String write(){
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        String s  = "";
        RLock rLock = lock.writeLock();
        try {
            rLock.lock();
            System.out.println("写锁加锁成功..." + Thread.currentThread().getId());
            s = UUID.randomUUID().toString();
            Thread.sleep(10000);
            stringRedisTemplate.opsForValue().set("writeValue", s);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String read(){
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.readLock();
        rLock.lock();
        try {
            System.out.println("读锁加锁成功..." + Thread.currentThread().getId());
            s = stringRedisTemplate.opsForValue().get("writeValue");
            Thread.sleep(10000);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
            System.out.println("读锁释放成功..." + Thread.currentThread().getId());
        }
        return s;
    }


    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch downLatch = redissonClient.getCountDownLatch("door");
        downLatch.trySetCount(3);
        downLatch.await();  // 等待闭锁都完成
        return "放假了";
    }


    @GetMapping("/go/{id}")
    @ResponseBody
    public String gogogo(@PathVariable("id") long id){
        RCountDownLatch downLatch = redissonClient.getCountDownLatch("door");
        downLatch.countDown();
        return id + "班的人都走了";
    }

    @GetMapping("/park")
    @ResponseBody
    public String park(){
        RSemaphore semaphore = redissonClient.getSemaphore("park");
        boolean acquire = semaphore.tryAcquire();
        if (acquire){
            // 执行业务
        }else{
            return "error";
        }
        return "ok=>"  + acquire;
    }

    @GetMapping("/go")
    @ResponseBody
    public String go(){
        RSemaphore semaphore = redissonClient.getSemaphore("park");
        semaphore.release();
        return "ok";
    }
}
